package com.lqk.demo.atomic.unsafe;

import com.lqk.demo.atomic.utils.UnsafeAccessorUtil;
import sun.misc.Unsafe;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lqk
 * @date 2022/1/4 16:11
 */
public class CustomizeAtomicData {
    public static void main(String[] args) {
        Account account = new AccountUnsafe(10000);
        Account.demo(account);
    }
}

class AccountUnsafe implements Account {

    private MyAtomicInteger balance;

    public AccountUnsafe(int balance) {
        this.balance = new MyAtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return balance.getValue();
    }

    @Override
    public void withdraw(Integer amount) {

        balance.decrement(-1*amount);
    }
}

interface Account {
    // 获取余额
    Integer getBalance();
    // 取款
    void withdraw(Integer amount);
    /**
     * 方法内会启动 1000 个线程，每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        long start = System.nanoTime();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(account.getBalance()
                + " cost: " + (end-start)/1000_000 + " ms");
    }
}

class MyAtomicInteger {
    private volatile int value;
    private static final long valueOffset;
    static final Unsafe UNSAFE;
    static {
       UNSAFE = UnsafeAccessorUtil.getUnsafe();
        try {
            valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public MyAtomicInteger(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void decrement(int delta) {
        while (true){
            int prev = value;
            int next = prev + delta;
            if (UNSAFE.compareAndSwapInt(this,valueOffset,prev,next)){
                break;
            }
        }
    }
}
